package com.qn.servlet;

import com.alibaba.fastjson2.JSON;
import com.qn.entity.Product;
import com.qn.entity.ResultBean;
import com.qn.service.ProductServiceImpl;
import com.qn.service.ProductServiceInter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    //创建业务层对象
    private ProductServiceInter<Product> productServiceInter = new ProductServiceImpl();
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建解构集对象
        ResultBean resultBean = new ResultBean(true);
        //获取修改的id(商品编号)
        String id = request.getParameter("id");
        //获取修改的flag(商品状态)
        String flag = request.getParameter("flag");
        try {
            //调用业务层修改的方法
            int row = productServiceInter.updateById(id, flag);
            //判断是否修改成功
            if (row > 0){
                //修改成功，返回数据，前段页面拿到数据进行判断。
                resultBean.setData("success");
            }else {
                //修改失败
                resultBean.setData("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultBean.setFlag(false);
            resultBean.setErrorMsg("修改服务器异常");
        }
        //回写数据
        response.getWriter().write(JSON.toJSONString(resultBean));

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
